package server;

import java.io.File;
import java.io.FileFilter;

public class Host {
    private String name;
    private String appBase;
    private Context[] context;

    public Host(String name, String appBase) {
        this.name = name;
        this.appBase = appBase;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAppBase() {
        return appBase;
    }

    public void setAppBase(String appBase) {
        this.appBase = appBase;
    }

    public Context[] getContext() {
        return context;
    }

    public void setContext(Context[] context) {
        this.context = context;
    }

    @Override
    public String toString() {
        return "Host{" +
                "name='" + name + '\'' +
                ", appBase='" + appBase + '\'' +
                ", context=" + context +
                '}';
    }

    public void init() throws Exception {
        if (appBase == null || appBase.length() == 0) {
            return;
        }

        // 构建file
        File file = new File(appBase);
        if (!file.exists() || !file.isDirectory()) {
            throw new Exception("wrong appBase");
        }

        // 创建context
        File[] contextDirectory = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isDirectory();
            }
        });
        if (contextDirectory == null) {
            return;
        }
        context = new Context[contextDirectory.length];
        for(int i = 0; i < contextDirectory.length; i++) {
            String name = contextDirectory[i].getName();
            String absolutePath = contextDirectory[i].getAbsolutePath();
            context[i] = new Context(name, absolutePath);
            context[i].init();
        }
    }

    public boolean process(Request request, Response response) throws Exception {
        // 本来是需要判断域名的，但是没有处理就算了
        for(int i = 0; i < context.length; i++) {
            if (context[i].process(request, response)) {
                return true;
            }
        }
        return false;
    }
}